package tq.com.tqstudent.ui.activity.mine;

import android.app.Activity;
import android.content.Intent;
import android.database.ContentObserver;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lib.common.base.BaseActivity;
import com.lib.common.utils.AppUtil;
import com.lib.common.utils.LogUtil;
import com.lib.common.utils.NavigationBarUtil;
import com.lzy.okgo.OkGo;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import tq.com.tqstudent.App;
import tq.com.tqstudent.R;
import tq.com.tqstudent.bean.BaseBean;
import tq.com.tqstudent.bean.ClassTypeBean;
import tq.com.tqstudent.bean.SimpleBaseBean;
import tq.com.tqstudent.bean.UserBean;
import tq.com.tqstudent.bean.UserInfo;
import tq.com.tqstudent.bean.params.UserInfoParams;
import tq.com.tqstudent.net.ok.DialogCallback;
import tq.com.tqstudent.utils.VarietyUtil;

/**
 * @Author rames
 * @date 2019/3/5 15:49
 */
public class ProfileActivity extends BaseActivity {
    @BindView(R.id.head_iv)
    ImageView headIV;
    @BindView(R.id.name_tv)
    TextView nameTV;
    @BindView(R.id.class_tv)
    TextView classTV;
    @BindView(R.id.name_edit)
    EditText nameEdit;
    private boolean isEdit = true; // 是否是在编辑状态
    private boolean isShow;
    private TextView sureTV;
    private String headID = ""; // 头像的id
    private ClassTypeBean currClass;
    private OptionsPickerView optionsPickerView;
    private ArrayList<ClassTypeBean> classList;

    public static void show(Activity activity) {
        Intent intent = new Intent(activity, ProfileActivity.class);
        Bundle bundle = new Bundle();
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @Override
    public int initLayout() {
        return R.layout.activity_profile;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        setTitle("基本信息");
        getState();
        registerNavigationBarObserver();
        currClass = new ClassTypeBean();
        classList = VarietyUtil.getAllClass();

        UserBean user = UserInfo.get();
        nameTV.setText(user.name);
        classTV.setText(VarietyUtil.getClassName(user.grade));
        nameEdit.setText(user.name);
        currClass.grade = user.grade;

        if(classTV.getText().toString().length() < 1){
            classTV.setText("点击选择班级");
        }

        getTitleView().setRight("编辑");
        getTitleView().setRightItemClick(view -> {
            if (isEdit) {
                edit();
                isEdit = false;
                getTitleView().setRight("保存");
            } else {
                updateTask(false);
            }
        });

        Glide.with(this).load(VarietyUtil.getHeadImgUri(UserInfo.getHeadImg())).into(headIV);
    }

    private void edit() {
        if (isEdit) {
            nameTV.setVisibility(View.GONE);
            nameEdit.setVisibility(View.VISIBLE);
        } else {
            nameEdit.setVisibility(View.GONE);
            nameTV.setVisibility(View.VISIBLE);
        }
    }

    // 修改头像回来
    @Subscribe
    public void onHeadEvent(SimpleBaseBean event){
        headID = event.fid;
        updateTask(true);
        UserInfo.setHeadImg(headID);
        Glide.with(this).load(App.getFileUrl(headID)).into(headIV);
    }

    @Override
    public void initData() {

    }

    @OnClick({R.id.head_iv, R.id.class_tv})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.head_iv:
                HeadImgActivity.show(this);
//                getPermission();
//                cropImage();
                break;

            case R.id.class_tv:
                AppUtil.hiddenKeyBoard(this, nameEdit);
                if(!isEdit){
                    ArrayList<String> list = new ArrayList<>();
                    for (int i = 0; i < classList.size(); i++) {
                        list.add(classList.get(i).className);
                    }
                    editClassDialog(list);
                }
                break;
        }
    }

    // 修改信息(是否是修改头像)
    private void updateTask(boolean isUpdateHead) {
        if (nameEdit.getText().toString().trim().length() < 1) {
            showToast("请先输入名字再保存");
            return;
        }

        ArrayList<UserInfoParams> list = new ArrayList<>();
        if(isUpdateHead){
            UserInfoParams pic = new UserInfoParams();
            pic.name = "pic";
            pic.val = headID;
            list.add(pic);
        } else {
            UserInfoParams name = new UserInfoParams();
            name.name = "name";
            name.val = nameEdit.getText().toString().trim();
            list.add(name);
            nameTV.setText(name.val);

            UserInfoParams clazz = new UserInfoParams();
            clazz.name = "grade";
            clazz.val = String.valueOf(currClass.grade);
            list.add(clazz);
            classTV.setText(VarietyUtil.getClassName(currClass.grade));
        }

        String json1 = new Gson().toJson(list);
        String json = "{\"field\":" + json1 + "}";
        LogUtil.e("json: " + json);

        OkGo.<BaseBean<ClassTypeBean>>post(App.getHttpUrl("api/user/update"))
                .tag(this)
                .upJson(json)
                .execute(new DialogCallback<ClassTypeBean>(ProfileActivity.this) {
                    @Override
                    public void handleSuccess(ClassTypeBean data) {
                        edit();
                        isEdit = true;
                        getTitleView().setRight("编辑");
                        ProfileActivity.this.showToast("保存成功");
                        if(!isUpdateHead) {
                            UserBean user = UserInfo.get();
                            user.grade = currClass.grade;
                            user.name = nameEdit.getText().toString().trim();
                            UserInfo.set(user);
                        }
                    }
                });
    }

    private void editClassDialog(final List<String> items) {
        optionsPickerView = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            classTV.setText(items.get(options1));
            currClass = classList.get(options1);

            optionsPickerView.dismiss();
        }).setLayoutRes(R.layout.view_edit_profile_class, v -> {
            sureTV = v.findViewById(R.id.sure_tv);

            setMargin();

            sureTV.setOnClickListener(v12 -> {
                optionsPickerView.returnData();
            });

            v.findViewById(R.id.cancel_tv).setOnClickListener(v1 -> optionsPickerView.dismiss());

            v.findViewById(R.id.title_layout).setOnClickListener(v13 -> { });
        })
                .isDialog(false)
                .setOutSideCancelable(true)
                .build();

        optionsPickerView.setPicker(items, null, null);
        optionsPickerView.show();
    }

    private void setMargin() {
        if (sureTV != null) {
            if (isShow) {//虚拟按键启用
                if (NavigationBarUtil.checkDeviceHasNavigationBar(this)) {
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) sureTV.getLayoutParams();
                    params.setMargins(0, 0, 0, NavigationBarUtil.getNavigationBarHeight(this));
                }
            } else {
                if (NavigationBarUtil.checkDeviceHasNavigationBar(this)) {
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) sureTV.getLayoutParams();
                    params.setMargins(0, 0, 0, 0);
                }
            }
        }
    }

    private ContentObserver mNavigationBarObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            getState();
        }
    };

    /**
     * 获取虚拟按键启用状态
     */
    private void getState() {
        int state = 0;
        if (NavigationBarUtil.isHuawei()) {//华为手机
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                state = Settings.System.getInt(getContentResolver(), "navigationbar_is_min", 0);
            } else {
                state = Settings.Global.getInt(getContentResolver(), "navigationbar_is_min", 0);
            }
            if (state == 1) {
                //导航键隐藏了
                isShow = false;

                setMargin();
            } else {
                isShow = true;
                //导航键显示了

                setMargin();
            }
        } else if (NavigationBarUtil.isXiaomi()) {//小手机
            state = Settings.Global.getInt(getContentResolver(), "force_fsg_nav_bar", 0);
            if (state == 1) {
                //导航键隐藏了
                isShow = false;

                setMargin();
            } else {
                isShow = true;
                //导航键显示了

                setMargin();
            }
        }

        LogUtil.e("onChange: " + state);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterNavigationBarObserver();
    }

    /**
     * 虚拟按键是否启用的监听
     */
    private void registerNavigationBarObserver() {
        if (NavigationBarUtil.isHuawei()) {//华为手机
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                getContentResolver().registerContentObserver(Settings.System.getUriFor
                        ("navigationbar_is_min"), true, mNavigationBarObserver);
            } else {
                getContentResolver().registerContentObserver(Settings.Global.getUriFor
                        ("navigationbar_is_min"), true, mNavigationBarObserver);
            }
        } else if (NavigationBarUtil.isXiaomi()) {//小米手机
//
//            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
//                mContext.getContentResolver().registerContentObserver(Settings.System.getUriFor
//                        ("force_fsg_nav_bar"), true, mNavigationBarObserver);
//            } else {
            getContentResolver().registerContentObserver(Settings.Global.getUriFor
                    ("force_fsg_nav_bar"), true, mNavigationBarObserver);
//            }
        }
    }

    private void unregisterNavigationBarObserver() {//取消监听
        getContentResolver().unregisterContentObserver(mNavigationBarObserver);
    }
}
